package cn.buildoncloud.labor.workermanapplet.business.modules.controller;


import cn.buildoncloud.labor.workermanapplet.business.modules.services.EquipmentService;
import cn.buildoncloud.labor.workermanapplet.business.modules.services.ProjectService;
import cn.buildoncloud.labor.workermanapplet.common.Constant;
import cn.buildoncloud.labor.workermanapplet.common.base.Result;
import cn.buildoncloud.labor.workermanapplet.util.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.nutz.http.Http;
import org.nutz.http.Response;
import org.nutz.json.Json;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 设备管理
 */
@RestController
@RequestMapping("/equipment")
public class EquipmentController {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Value("${webSystemIP}")
    private String webSystemIP;

    @Autowired
    private EquipmentService equipmentService;

    @Autowired
    private ProjectService projectService;

    /**
     * 通过二维码获取设备信息
     * @param uniqueIdentity
     * @param projectId
     * @param equipmentModelId
     * @return
     */
    @RequestMapping("/getEquipmentByQRCode")
    public Object getEquipmentByQRCode(@RequestParam String uniqueIdentity,
                           @RequestParam String projectId,
                           @RequestParam String equipmentModelId){
        try{

            boolean existenceModel = equipmentService.existenceEquipmentModelId(equipmentModelId);
            if (!existenceModel){
                return Result.error("设备型号不存在");
            }

            Map<String, Object> createEquipmentParameterMap = new HashMap<>();
            createEquipmentParameterMap.put("uniqueIdentity", uniqueIdentity);
            createEquipmentParameterMap.put("equipmentModelId", equipmentModelId);

            Map<String, Object> resultMap = projectService.getUnitIdById(Long.parseLong(projectId));
            createEquipmentParameterMap.put("useUnitId", resultMap.get("unit_id"));

            boolean existenceEquipment = equipmentService.existenceEquipment(uniqueIdentity);



            if (!existenceEquipment) {
//            Response response = Http.post2(webSystemIP + "/equipment/createEquipment", createEquipmentParameterMap, 1000 * 60);
//            Result result = Json.fromJson(Result.class, response.getContent());

                String result = HttpUtil.post(webSystemIP + "/equipment/createEquipment", createEquipmentParameterMap, 1000 * 60);
                JSONObject jsonObject = JSONObject.parseObject(result);

                if (jsonObject != null && jsonObject.getInteger("code") != 0) {
                    return result;
                }
            }
            Map<String, Object> getEquipmentParameterMap = new HashMap<>();
            getEquipmentParameterMap.put("uniqueIdentity", uniqueIdentity);
            getEquipmentParameterMap.put("projectId", projectId);
//        Response response = Http.post2(webSystemIP + "/equipment/equipmentByUniqueIdentityAndProjectId", getEquipmentParameterMap, 1000 * 60);
//
//        Result result = Json.fromJson(Result.class, response.getContent());

            String result = HttpUtil.post(webSystemIP + "/equipment/equipmentByUniqueIdentityAndProjectId", getEquipmentParameterMap, 1000 * 60);

            return result;
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error("接口异常");
        }

    }

    /**
     * 通过唯一标识获取设备信息
     * @param uniqueIdentity
     * @param projectId
     * @return
     */
    @RequestMapping("/getEquipmentByUniqueIdentity")
    public Object getEquipmentByUniqueIdentity(@RequestParam String uniqueIdentity,
                               @RequestParam String projectId){
        try{

            boolean existenceEquipment = equipmentService.existenceEquipment(uniqueIdentity);

            if (!existenceEquipment){
                return Result.error("设备编号不存在");
            }

            Map<String, Object> getEquipmentParameterMap = new HashMap<>();
            getEquipmentParameterMap.put("uniqueIdentity", uniqueIdentity);
            getEquipmentParameterMap.put("projectId", projectId);
            //Response response = Http.post2(webSystemIP + "/equipment/equipmentByUniqueIdentityAndProjectId", getEquipmentParameterMap, 1000 * 60);
            String result = HttpUtil.post(webSystemIP + "/equipment/equipmentByUniqueIdentityAndProjectId", getEquipmentParameterMap, 1000 * 60);

            if (!StringUtils.hasText(result)){
                return Result.error("获取设备信息失败");
            }

            //Result result = Json.fromJson(Result.class, response.getContent());

            return result;
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error(Constant.API_OPERATION_FAILED);
        }


    }

    /**
     * 设备进场
     * @param equipmentId
     * @param projectId
     * @return
     */
    @RequestMapping("/arriving")
    public Object arriving(@RequestParam String equipmentId,
                           @RequestParam String projectId,
                           @RequestParam Integer businessType,
                           @RequestParam String doorAccessInOutFlag,
                           @RequestParam(required = false) String note){
        try{
            if (!StringUtils.hasText(projectId)){
                return Result.error("projectId is null");
            }
            if (!StringUtils.hasText(equipmentId)){
                return Result.error("equipmentId is null");
            }
            boolean isDoorAccessInOutFlag = "in".equals(doorAccessInOutFlag) || "out".equals(doorAccessInOutFlag);

            if (!isDoorAccessInOutFlag){
                return Result.error("doorAccessInOutFlag is not in or out");
            }

            Map<String, Object> arrivingParameterMap = new HashMap<>();
            arrivingParameterMap.put("equipmentId", equipmentId);
            arrivingParameterMap.put("projectId", projectId);
            arrivingParameterMap.put("businessType", businessType);
            arrivingParameterMap.put("doorAccessInOutFlag", doorAccessInOutFlag);
            arrivingParameterMap.put("note", note);

//        Response response = Http.post2(webSystemIP + "/equipment/equipmentBindProject", arrivingParameterMap, 1000 * 60);
//
//        Result result = Json.fromJson(Result.class, response.getContent());
            String result = HttpUtil.post(webSystemIP + "/equipment/equipmentBindProject", arrivingParameterMap, 1000 * 60);
            return result;
        }catch (Exception e) {
            log.error(e.getMessage(),e);
            return Result.error(Constant.API_NETWORK_ANOMALY);
        }
    }

    /**
     * 获取设备列表
     * @param pageNo
     * @param pageSize
     * @param projectId
     * @param uniqueIdentity
     * @param businessType
     * @return
     */
    @RequestMapping("/listEquipment")
    public Object listEquipment(@RequestParam String pageNo,
                                @RequestParam String pageSize,
                                @RequestParam String projectId,
                                @RequestParam(required = false) String uniqueIdentity,
                                @RequestParam(required = false) String businessType){
        try{
            Map<String, Object> parameterMap = new HashMap<>();
            parameterMap.put("pageNo", pageNo);
            parameterMap.put("pageSize", pageSize);
            parameterMap.put("projectId", projectId);
            if (StringUtils.hasText(uniqueIdentity)){
                parameterMap.put("search.uniqueIdentity", uniqueIdentity);
            }
            if (StringUtils.hasText(businessType)){
                parameterMap.put("search.businessType",  Integer.parseInt(businessType));
            }

//        Response response = Http.post2(webSystemIP + "/equipment/equipmentListByProjectId", parameterMap, 1000 * 60);
//
//        Result result = Json.fromJson(Result.class, response.getContent());
            String result = HttpUtil.post(webSystemIP + "/equipment/equipmentListByProjectId", parameterMap, 1000 * 60);
            return result;
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return Result.error(Constant.API_NETWORK_ANOMALY);
        }
    }

    /**
     * 设备退场
     * @param projectId
     * @param equipmentId
     * @return
     */
    @RequestMapping("/equipmentUnBindProject")
    public Object equipmentUnBindProject(@RequestParam String projectId,
                                         @RequestParam String equipmentId){
        try{
            Map<String, Object> parameterMap = new HashMap<>();
            parameterMap.put("projectId", projectId);
            parameterMap.put("equipmentId", equipmentId);

//        Response response = Http.post2(webSystemIP + "/equipment/equipmentUnBindProject", parameterMap, 1000 * 60);
//
//        Result result = Json.fromJson(Result.class, response.getContent());
            String result = HttpUtil.post(webSystemIP + "/equipment/equipmentUnBindProject", parameterMap, 1000 * 60);
            return result;
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return Result.error(Constant.API_NETWORK_ANOMALY);
        }

    }

}
